﻿/**
 * by leili
 */

function inputInteger(evt){
    var keyCode = evt.keyCode;
	//var keyValue = String.fromCharCode(keyCode);
	if(keyCode == 8 ||  keyCode == 46 || keyCode == 37 || keyCode == 39 || keyCode == 9) return true;
	if(evt.shiftKey) return false;
    if(!(keyCode<=57&&keyCode>=48) && !(keyCode<=105&&keyCode>=96)) return false;
	return true;
}




//查找文档中所有select元素,除withoutSelects以外.
function findSelects(withoutSelects){
  var result = new Array();
  var withoutElments =  $A(withoutSelects);
  var selects = document.getElementsByTagName("select");
  $A(selects).each(function(value,index){
	var flag = true;
	withoutElments.each(function(element){
	  var tempEles = element.tagName && element.tagName.toLowerCase()=="select"?[element]:$A(element);
	  tempEles.each(function(trueEle){
	    if(trueEle == value){
			//alert("value=" + value.name +"   trueEle=" + trueEle.name + "  bijiao=" + (trueEle != value));
		  flag = false;
		}
	  });
	});
	if(flag) result.push(value);
  });
  return result;
}


function disableBodyAllFormElement(){
  $A(findBodyAllFormElements()).each(function(value){
	 value.disabled = true;
  });
}

function enableBodyAllFormElement(){
  $A(findBodyAllFormElements()).each(function(value){
	 value.disabled = false;
  });
}

//可以把除外的元素的id或者实例或者实例的Array通过参数传给函数
function hideAllSelects(){
	findSelects(arguments).each(function(value,index){
       Element.hide(value);
	});
}

//可以把除外的元素的id或者实例或者实例的Array通过参数传给函数
function showAllSelects(){
	findSelects(arguments).each(function(value,index){
       Element.show(value);
	});
}

function disableAllSelects(){
	findSelects(arguments).each(function(value,index){
       value.disabled = true;
	});
}

function enableAllSelects(){
	findSelects(arguments).each(function(value,index){
       value.disabled = false;
	});
}



//--------------------------------------------------------- 选择组件 -------------------------------------------------------

function simpleClick(event){
	processMouseClick(event,1);
}


function processMouseClick(event,type){/* type:0 or null is mulriple,1 is simple*/
  if(!event) event = window.event;
  var source = Event.findElement(event,"tr");
  var table = Event.findElement(event,"table");
  if(!table.markTrs) table.markTrs = new Array();
  if(!type)
    if(event.shiftKey) pressShiftKey(source,table,event);
    else if(event.ctrlKey) pressCtrlKey(source,table);
    else noPress(source,table);
  else
    noPress(source,table);
  
}

function noPress(source,table){
	var i = 0;
	table.markTrs.each(function(value,index){
	  if(value == source) i++;
	  else value.className = value.initClassName;
	});
	
	if(i==0){
	  source.initClassName = source.className;
      source.className = "trActive";
	}
	table.markTrs.clear();
	table.markTrs.push(source);
	table.clickElementLast = source;
}

function pressCtrlKey(source,table){
	 var tempArray = new Array();
	 var i = 0;
	 table.markTrs.each(function(value,index){
	   if(value==source){
		 i++;
	     source.className = source.initClassName;
	   }else{
		 tempArray.push(value);
	   }
	 });
	 
	 if(i==0){
		 //表示当前事件源对象，不在选中列表中




	   source.initClassName = source.className;
	   source.className = "trActive";
	   table.markTrs.push(source);
	 }else{
	   table.markTrs = tempArray;
	 }
	 table.clickElementLast = source;
}

function pressShiftKey(source,table,event){
  //var lastElement = table.markTrs.last();
  if(table.clickElementLast){
	//按住fhift时，已有元素选中。




	if(!event.ctrlKey){
      table.markTrs.each(function(value,index){
        value.className = value.initClassName;
      });
      table.markTrs.clear();
	}

    
	var temp = table.clickElementLast;
	temp.className = temp.initClassName;
	
	function change(previousOrNext){
	  while(temp!=source){
	   if(temp.className != "trActive"){
	     temp.initClassName = temp.className;
	     temp.className = "trActive";
	     table.markTrs.push(temp);
	   }
	   temp = temp[previousOrNext];
	  }
	  
	  if(temp==source && temp.className != "trActive"){
	    source.initClassName = source.className;
	    source.className = "trActive";
	    table.markTrs.push(source);
	  }
	}
    if(parseInt(temp.index)>parseInt(source.index)){
	  change("previousSibling");
	}else{
	  change("nextSibling");
	}
  }else{
	 //第一次按住shift键时，还没有元素选中时。




	 source.initClassName = source.className;
	 source.className = "trActive";
	 table.markTrs.push(source); 
  }
}
//--------------------------------------------------------- 选择组件 -------------------------------------------------------


function calculateCenter(element,width,height){
  Element.toCenter(element,width,height);
}


/**
  *根据值设定被选中的元素。当值在所有option中没有时，保持当前状态不变！
  */
function setSelectElementSelected(selectId,targetValue){
  var temp  = selectId;
  if(selectId.tagName == undefined){
	temp = document.getElementById(selectId); 
  }
  var tempArray = temp.options;
  for(var n=0;n<tempArray.length;n++){
    if(tempArray[n].value == targetValue){
      if(document.uniqueID){
        temp.selectedIndex = n;
      }else{
	    tempArray[n].selected = true;
	  }
	  break;
	}
  }
} 
 

function setRadioSelected(radioName,targetValue){
    var tempArray = document.getElementsByName(radioName);
    for(var m=0;m<tempArray.length;m++){
	  if((targetValue  == tempArray[m].value)){
	    tempArray[m].checked = true;
		break;
	  }
	}  
}


function getRadioSelected(radioName){
    var result = null;
    var tempArray = document.getElementsByName(radioName);
    for(var m=0;m<tempArray.length;m++){
	  if(tempArray[m].checked){
	    result =  tempArray[m].value;
		break;
	  }
	}
	return result;
}



function setCheckboxSelected(checkboxName,targetValue){
    var tempArray = document.getElementsByName(checkboxName);
    for(var m=0;m<tempArray.length;m++){
	  if(targetValue.indexOf(tempArray[m].value) != -1){
	    tempArray[m].checked = true;
	  }
	}  
}

var HtmlTable = Class.create();
HtmlTable.prototype = {
  initialize: function(page,templet) {
    var htable = document.createElement("table");
    Object.copyMembers(htable,templet);
    var htbody = document.createElement("tbody");
    htable.appendChild(htbody);
    if(templet.header!=null) this.buildHeader(templet.header,htbody,page);
    if(templet.data!=null) this.buildData(templet.data,htbody,page);
    if(templet.footer!=null) this.buildFooter(templet.footer,htbody,page);
	  this.htable = htable;
  },
  buildTree: function(templet,node,item,page,index){
    switch(templet.tag){
      case "text":
        var text = document.createTextNode(templet.body.evalEls(item,page,index));
        node.appendChild(text);
        Object.copyMembers(text,templet,item,page,index);
        break;
      case "option":
        var opt = document.createElement(templet.tag);
        if(document.uniqueID) node.add(opt); else node.appendChild(opt);
        Object.copyMembers(opt,templet,item,page,index);
        break;
     default:
        var other = document.createElement(templet.tag);
        Object.copyMembers(other,templet,item,page,index);
        node.appendChild(other);
        if(templet.body){
          if(typeof templet.body == "string" || templet.body instanceof String){
            other.appendChild(document.createTextNode(templet.body.evalEls(item,page,index)));
          }else{
            if(!(templet.body instanceof Array)) templet.body = [templet.body];
            var temp = this;
            templet.body.each(function(_templet){
              temp.buildTree(_templet,other,item,page);
            });
          }
        }  
    }
  },
  buildHeader: function(templet,htbody,page){
    this.buildTree(templet,htbody,null,page);
  },
  buildData: function(templet,htbody,page) {
    var temp = this;
	var list = page instanceof Array?page:page.list;
    list.each(function(item,index){
      temp.buildTree(templet,htbody,item,page,index);
    });
  },
  buildFooter: function(templet,htbody,page){
    this.buildTree(templet,htbody,null,page);
  }
};

var TableFactory = Class.create();
TableFactory.getInstance = function(page,templet){
  return new HtmlTable(page,templet).htable;
}


//主要用于创建表格时，tr事件动作时，搜索触发事情的tr元素
function searchTrNode(event){
		var tempNode = event?event.currentTarget:window.event.srcElement;
		while(tempNode.tagName.toUpperCase() != "TR"){
		  tempNode = tempNode.parentNode;
		}
		return tempNode;
}


function removeChildNodes(element){
	var eles = $A(element.childNodes);
	eles.each(function(value){
	  element.removeChild(value);
	});
}

function checkEnter(evt){
  if(evt.keyCode == 13){
    return true;
  }
  return false;
}

function getMaxPage(maxRowCount,rowsPerPage) {
  var a = parseInt(maxRowCount / rowsPerPage);
  if (maxRowCount % rowsPerPage != 0) {
    a = parseInt(maxRowCount / rowsPerPage) + 1;
  } else if (maxRowCount < rowsPerPage) {
    a = 1;
  }
  return a;
}

function renderPagination(jsonObject,container,jumpTargetPage/* function point */,className,classInput){
  //window.jumpTargetPage = jumpTargetPage;
  container = $(container);
  
  Element.removeChilds(container);
  
  var htable = document.createElement("table");
  if(className != null) htable.className = className;
  container.appendChild(htable);
  
  var htbody = document.createElement("tbody");
  htable.appendChild(htbody);
  
  var htr = document.createElement("tr");
  htbody.appendChild(htr);
  
  var htd = document.createElement("td");
  htr.appendChild(htd);
  
  htd.innerHTML = res.display + "&nbsp;<select disabled='true' id='rowsPerPage' class='"+ classInput +"'>"+
                     //"<option value='10'>10</option>"+
					 "<option selected='selected' value='20'>20</option>" + "<option value='40'>40</option>"+
					 "<option value='60'>60</option>" + "<option value='80'>80</option>"+
					 "<option value='100'>100</option>" + "</select>&nbsp;"+ res.items +"&nbsp;";
					 
  var _rowsPerPage = htd.getElementsByTagName('select')[0];
  setSelectElementSelected(_rowsPerPage,jsonObject.rowsPerPage);
  //_rowsPerPage.onchange = function(event){jumpTargetPage(jsonObject.curPage,this.value)};
  Event.addListener(_rowsPerPage,'onchange',function(event){jumpTargetPage(jsonObject.curPage,this.value)});
  
  var maxPage = getMaxPage(jsonObject.maxRowCount,jsonObject.rowsPerPage);

  htd.appendChild(document.createTextNode(res.at+" "));

  var currentPage = document.createElement("span");
  currentPage.id = "currentPage";
  currentPage.style.color = "#FF6600";
  currentPage.innerHTML = jsonObject.curPage?jsonObject.curPage:"0";
  htd.appendChild(currentPage);
  
  var text = document.createTextNode("/");
  htd.appendChild(text);  
  
  var countPage = document.createElement("span");
  countPage.id = "currentPage";
  countPage.style.color = "#FF6600";
  countPage.innerHTML = maxPage?maxPage:"0";
  htd.appendChild(countPage);
  
  htd.appendChild(document.createTextNode(" "+res.page));
  htd.appendChild(document.createTextNode("   "));
  htd.appendChild(document.createTextNode(res.pageCount));
  
  var _count = document.createElement("span");
  _count.id = "currentPage";
  _count.style.color = "#FF6600";
  _count.innerHTML = jsonObject.maxRowCount?jsonObject.maxRowCount:"0";
  htd.appendChild(_count);

  htd.appendChild(document.createTextNode("   "));
  
  if(jsonObject.curPage > 1){
      var firstPage = document.createElement("a");
      htd.appendChild(firstPage);
	    //firstPage.href = "javascript:jumpTargetPage(1)";
	  firstPage.style.cursor = "pointer";
	  firstPage.style.color = "#FF6600";
	  //firstPage.onclick = function(event){jumpTargetPage(1,_rowsPerPage.value)};
	  Event.addListener(firstPage,'onclick',function(event){jumpTargetPage(1,_rowsPerPage.value)});
	  firstPage.innerHTML = "&lt;&lt;";
	    
      htd.appendChild(document.createTextNode("  "));
      
	  var previousPage = document.createElement("a");
	  htd.appendChild(previousPage);
	  //previousPage.href = "javascript:jumpTargetPage(" + (jsonObject.curPage-1) + ")";
	  previousPage.style.cursor = "pointer";
	  previousPage.style.color = "#FF6600";
	  //previousPage.onclick = function(event){jumpTargetPage(jsonObject.curPage-1,_rowsPerPage.value)};
	  Event.addListener(previousPage,'onclick',function(event){jumpTargetPage(jsonObject.curPage-1,_rowsPerPage.value)});
      previousPage.innerHTML = "&lt;";
  }else{
    htd.appendChild(document.createTextNode("<<  <"));
  }
  
  htd.appendChild(document.createTextNode(" "));
  
  if(jsonObject.curPage < maxPage){
      var nextPage = document.createElement("a");
      htd.appendChild(nextPage);
	  //nextPage.href = "javascript:jumpTargetPage(" + (jsonObject.curPage+1) + ")";
	  nextPage.style.cursor = "pointer";
	  nextPage.style.color = "#FF6600";
	  //nextPage.onclick = function(event){jumpTargetPage(jsonObject.curPage+1,_rowsPerPage.value)};
	  Event.addListener(nextPage,'onclick',function(event){jumpTargetPage(jsonObject.curPage+1,_rowsPerPage.value)});
      nextPage.innerHTML = "&gt;";
      
      htd.appendChild(document.createTextNode("  "));
      
      var lastPage = document.createElement("a");
      htd.appendChild(lastPage);
	    //lastPage.href = "javascript:jumpTargetPage(" + maxPage + ")";
	  lastPage.style.cursor = "pointer";
	  lastPage.style.color = "#FF6600";
	  //lastPage.onclick = function(event){jumpTargetPage(maxPage,_rowsPerPage.value)};
	  Event.addListener(lastPage,'onclick',function(event){jumpTargetPage(maxPage,_rowsPerPage.value)});
	  lastPage.innerHTML = "&gt;&gt;";
  }else{
    htd.appendChild(document.createTextNode(">  >>"));
  }
  
  var ctext = document.createTextNode("  "+res.pageJump);
  htd.appendChild(ctext);
  
  var paginationInput = document.createElement("input");
  paginationInput.type = "text";
  if(classInput != null) paginationInput.setAttribute("className",classInput);
  paginationInput.id = "pagination";
  paginationInput.size = 2;
  paginationInput.maxLength = 3;
  paginationInput.value = jsonObject.curPage;
  paginationInput.disabled = true;
  Event.addListener(paginationInput,'onblur',function(event){jumpTargetPage(this.value,_rowsPerPage.value);});

  Event.addListener(paginationInput,'onkeypress',function(event){
	  if(checkEnter(event?event:window.event)){
	    jumpTargetPage(this.value,_rowsPerPage.value);
	  }
  });
  
  htd.appendChild(paginationInput);


}
function getHTML(url,targetElement){
  targetElement = $(targetElement);
  function reportError(request){
    alert('Sorry. There was an error.');
  }
  var pars = 'fox='+new Date().getTime();
  new Ajax.Updater({success: targetElement},url,{method: 'get',parameters:pars,onFailure:reportError,evalScripts:true,asynchronous:false});
}


function showError(element,error){
	$(element).show();
	$(element).className="error";
	if(error && error.title){
		$(element).innerHTML = "<table border='0' cellspacing='0' cellpadding='0'><tr>"+
		"<td width='16' style='font-weight:bold'><img src='" + Global.CONTEXT_PATH + "/images/error.gif' border='0' /></td>"+
		"<td align='left'>" + error.title + "</td></tr>" +
		"<tr><td></td><td>" + error.detail + "</td></tr>"
		"</table>";
	}else{
		$(element).innerHTML = "<table border='0' cellspacing='0' cellpadding='0'><tr>"+
		"<td width='16'><img src='" + Global.CONTEXT_PATH + "/images/error.gif' border='0' /></td>"+
		"<td align='left'>" + (error||"") + "</td></tr></table>";
	}
	setTimeout("closeMessage()",2000);	
}

function showSuccess(element,msg){
	$(element).show();
	$(element).className="success";
	//$(element).innerHTML = "<!--img src='/images/success.gif' border='0'-->" + msg;
	$(element).innerHTML = "<table border='0' cellspacing='0' cellpadding='0'><tr><td width='17'><img src='" + Global.CONTEXT_PATH + "/images/success.png' border='0' /></td><td align='left'>&nbsp;&nbsp;" + (msg||"") + "</td></tr></table>";
	setTimeout("closeMessage()",2000);
}
function closeMessage(element){
	$('statusBar').hide();
}
function showMessage(element,msg,type){
	if(type=="0"){
		if(errMsgs!=""){
			showSuccess(element, msg);
		}else{
			showSuccess(element, "数据保存成功！");
		}
	}
	if(type=="1"){
	   if(errMsgs!=""){
		   showError(element, msg);	
	   }else{
		   showError(element, "操作失败！");
		} 
	}	
}


function addListener(element, e, fn) {
	if (window.addEventListener) {
		element.addEventListener(e, fn, false);
	} else if (window.detachEvent) {
		element.attachEvent("on" + e, fn);
	}
}
function removeListener(element, e, fn) {
    if (window.removeEventListener) {
    	element.removeEventListener(e, fn, false);
    } else if (window.detachEvent) {
    	element.detachEvent("on" + e, fn);
    }
}

function documentReady(fn){
	if(Prototype.Browser.IE){
		addListener(document,"readystatechange", function() {
		    if (document.readyState == 'complete') {
		    	fn();
		    }
		});
	}else{
		addListener(document, "DOMContentLoaded", fn);
	}
	
}

function img_zoom_re(obj,frame_width,frame_height) 
{
    var img=null;
    img=document.createElement("img");
    img.src=obj.src;
    if(img.width>frame_width || img.height>frame_height){
        if (img.width/frame_width > img.height/frame_height)
        {
            obj.width = frame_width;
            obj.height = (frame_width * img.height)/img.width;
        }
        else
        {
            obj.width = (frame_height * img.width)/img.height;
            obj.height = frame_height;
        }
    }
    else
    {
        obj.width = img.width;
        obj.height = img.height;
    }
}

function getElementListById(id, tag, parentId){
	var parent=null;
	if(parentId){
		parent=$(parentId);
	}else{
		parent=document;
	}
	var elements=parent.getElementsByTagName(tag);
	var resultList=new Array();
	var index=0;
	for(var i=0; i<elements.length; i++){
		if(elements[i].id==id){
			resultList[index++]=elements[i];
		}
	}
	return resultList;	
}

function getElementListByClassName(className, tag, parentId){
	var parent=null;
	if(parentId){
		parent=document.getElementById(parentId);
	}else{
		parent=document;
	}
	var elements=parent.getElementsByTagName(tag);
	var resultList=new Array();
	var index=0;
	for(var i=0; i<elements.length; i++){
		if(elements[i].className==className){
			resultList[index++]=elements[i];
		}
	}
	return resultList;	
}

function insertAfter( referenceNode, newNode )
{
	if(referenceNode.nextSibling){
		referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
	}else{
		referenceNode.appendChild( newNode);
	}
}

function insertBefore(referenceNode, newNode) {

    return referenceNode.parentNode.insertBefore(newNode, referenceNode); 
}

function checkSelect(check, checks){
	 
	 var selected=check.checked;
	 if(!checks.length){
		 checks.checked=selected;
		 return ;
	}
	 for(var i=0; i<checks.length; i++){
		 checks[i].checked=selected;
	}
}